﻿using DevExpress.ExpressApp.ConditionalAppearance;
using DevExpress.ExpressApp.DC;
using DevExpress.ExpressApp.Editors;
using DevExpress.Persistent.Validation;
using Newtonsoft.Json;

namespace EasyXaf.LowCode.RulesEngineEditors.Models;

[DomainComponent]
[XafDisplayName("参数")]
public class ScopedParamObject : ParamObject
{
    private ExpressionType _expressionType;
    private string _targetObject;
    private string _expression;

    [XafDisplayName("表达式类型")]
    [JsonConverter(typeof(ExpressionTypeConverter))]
    public ExpressionType ExpressionType
    {
        get => _expressionType;
        set => SetPropertyValue(ref _expressionType, value);
    }

    [Appearance("当表达式类型不为Criteria时隐藏", Criteria = "[ExpressionType] != 1", Visibility = ViewItemVisibility.Hide)]
    [XafDisplayName("目标对象")]
    public string TargetObject
    {
        get => _targetObject;
        set => SetPropertyValue(ref _targetObject, value);
    }

    [RuleRequiredField]
    [XafDisplayName("表达式")]
    public string Expression
    {
        get => _expression;
        set => SetPropertyValue(ref _expression, value);
    }

    public override IEnumerable<ValidationResult> Validate()
    {
        foreach (var validationResult in base.Validate())
        {
            yield return validationResult;
        }

        if (ExpressionType == ExpressionType.Criteria && string.IsNullOrWhiteSpace(TargetObject))
        {
            yield return new ValidationResult("参数的表达式类型为Criteria时，目标对象不能为空", ValidationResultLevel.Error);
        }

        if (string.IsNullOrWhiteSpace(Expression))
        {
            yield return new ValidationResult("参数的表达式不能为空", ValidationResultLevel.Error);
        }
    }
}
